package com.nova.android.tvlauncher.ui.adapter.atv

import android.view.KeyEvent
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.leanback.widget.HorizontalGridView
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.constants.ConstantsAtv.REMOVE_FAVORITE_APPS
import com.nova.android.tvlauncher.databinding.ItemAppChildAtvBinding
import com.nova.android.tvlauncher.databinding.ItemAppParentAtvBinding
import com.nova.android.tvlauncher.ext.launchCommonRightPanelAtvActivity
import com.nova.android.tvlauncher.ext.toggle16to9Scale
import com.nova.android.tvlauncher.ui.activity.atv.CommonRightPanelAtvActivity
import com.nova.android.tvlauncher.ui.dialog.ext.showHomeMenuDialog
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.bean.FavoriteApp
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.createDrawable
import com_github_lib_base.ext.height
import com_github_lib_base.ext.isBanner
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.rv.BindAdapter
import com_github_lib_base.ext.rv.removeModelAt
import com_github_lib_base.ext.rv.setup
import sendLiveEventData
import java.util.Collections

object HomeListFavoriteAppAtvAdapter {
    fun bindData(
        itemParentBinding: ItemAppParentAtvBinding,
        apps: List<FavoriteApp>,
    ) {

        /*itemParentBinding.rvHorizontal.setWindowAlignment(BaseGridView.WINDOW_ALIGN_BOTH_EDGE);

        //itemParentBinding.rvHorizontal.setWindowAlignmentOffset(-50); // 负偏移量，向左移动对齐点
        //itemParentBinding.rvHorizontal.setWindowAlignmentOffsetPercent(0f); // 可根据需要调整百分比
        itemParentBinding.rvHorizontal.setClipChildren(false); // 禁用子视图裁剪
        itemParentBinding.rvHorizontal.setClipToPadding(false); // 禁用 padding 区域裁剪*/
        //itemParentBinding.leftMenu.visibility = INVISIBLE
        itemParentBinding.leftMenu.leftArrow().visibility = INVISIBLE
        itemParentBinding.rvHorizontal.height(ViewGroup.LayoutParams.WRAP_CONTENT)
        itemParentBinding.rvHorizontal.setup(apps) {
            addType(FavoriteApp::class, R.layout.item_app_child_atv)
            onBind {
                itemParentBinding.tvDetailTitle.isVisible = false
                itemParentBinding.tvDetailSubtitle.isVisible = false
                val itemBinding = getBinding<ItemAppChildAtvBinding>()
                val item = getModel<FavoriteApp>()

                itemBinding.tvAppName.text = item.displayName
                showIcon(item, itemBinding)


                itemClick(item, itemBinding, itemParentBinding.rvHorizontal, this)
                itemMoveEvent(item, itemBinding, this)
                itemBinding.rlIcon.setOnFocusChangeListener { _, hasFocus ->
                    itemBinding.tvAppName.visibility = if (hasFocus) VISIBLE else INVISIBLE
                    itemBinding.rlIcon.toggle16to9Scale(modelPosition == 0, hasFocus, 1.28f)
                        //itemBinding.tvAppName.fadeView(if (hasFocus) true else false)

                    if (hasFocus) {

                           // itemParentBinding.tvTitle.height(com.codeZeng.lib_dimen.R.dimen.qb_px_23.dimenValue())


                    } else {

                           // itemParentBinding.tvTitle.height(ViewGroup.LayoutParams.WRAP_CONTENT)

                        //itemParentBinding.tvTitle.height(ViewGroup.LayoutParams.WRAP_CONTENT)
                    }

                    itemBinding.tvAppName.isSelected = hasFocus
                }

            }
        }
        //itemParentBinding.rvHorizontal.itemAnimator = null


    }

    private fun showIcon(item: FavoriteApp, itemBinding: ItemAppChildAtvBinding) {
        val drawable = item.createDrawable(appContext)
        if (!item.isAdd) {
            itemBinding.ivAdd.isVisible = false
            if (drawable.isBanner()) {
                // 横屏 Banner 的处理逻辑
                itemBinding.ivBigicon.scaleType = ImageView.ScaleType.FIT_CENTER
                itemBinding.ivBigicon.setImageDrawable(drawable)
                itemBinding.ivIcon.isVisible = false
                itemBinding.ivBigicon.isVisible = true
            } else {
                // Icon 的处理逻辑
                itemBinding.ivIcon.setImageDrawable(drawable)
                itemBinding.ivIcon.isVisible = true
                itemBinding.ivBigicon.isVisible = false
            }
        } else {
            itemBinding.ivAdd.isVisible = true
            itemBinding.ivIcon.isVisible = false
            itemBinding.ivBigicon.isVisible = false
        }
    }

    private fun itemMoveEvent(
        item: FavoriteApp,
        itemBinding: ItemAppChildAtvBinding,
        binding: BindAdapter
    ) {
        itemBinding.rlIcon.setOnKeyListener { _, keyCode, event ->
            if (!isMoveLocalAppStatus) {
                if (binding.modelPosition == binding.models.size - 1) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) return@setOnKeyListener true
                }
                return@setOnKeyListener false
            }
            if (event.action == KeyEvent.ACTION_DOWN) {
                when (keyCode) {
                    KeyEvent.KEYCODE_DPAD_LEFT -> {
                        if (binding.modelPosition == 0) {
                            return@setOnKeyListener true
                        }
                        // 向上替换（与上一个 Item 交换）
                        val newPosition = binding.modelPosition - 1
                        binding.swapItems(binding.modelPosition, newPosition)

                        return@setOnKeyListener true
                    }

                    KeyEvent.KEYCODE_DPAD_RIGHT -> {

                        if (binding.modelPosition >= binding.models.size - 2) {

                            return@setOnKeyListener true
                        }
                        // 向下替换（与下一个 Item 交换）
                        binding.swapItems(binding.modelPosition, binding.modelPosition + 1)

                        return@setOnKeyListener true
                    }

                    KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_CENTER -> {
                        isMoveLocalAppStatus = false

                        return@setOnKeyListener true

                    }
                }
            }
            false
        }
    }

    private fun itemClick(
        item: FavoriteApp,
        itemBinding: ItemAppChildAtvBinding,
        rvHorizontal: HorizontalGridView,
        adapter: BindAdapter
    ) {
        if (item.isAdd) {
            itemBinding.rlIcon.clickNoRepeat {
                CommonRightPanelAtvActivity.Companion.SELECT_APP_FRAGMENT.launchCommonRightPanelAtvActivity()
            }
        } else {
            itemBinding.rlIcon.clickNoRepeat {
                item.packageName.openApp()
            }
            itemBinding.rlIcon.setOnLongClickListener {
                itemBinding.rlIcon.showHomeMenuDialog {
                    clickOpen {
                        item.packageName.openApp()
                    }

                    clickMove {
                        //移动应用
                        isMoveLocalAppStatus = true
                    }
                    clickRemove {
                        var appInfo: FavoriteApp?=null
                       // rvHorizontal.removeModelAt(adapter.modelPosition) // 删除数据
                        val favouriteApps = AppCache.favoriteAppList
                        for (i in favouriteApps.size - 1 downTo 0) {
                            if (favouriteApps[i].packageName == item.packageName) {
                                appInfo = favouriteApps[i]
                                favouriteApps.removeAt(i)
                                break
                            }
                        }
                        AppCache.favoriteAppList = favouriteApps
                        if(appInfo!=null){
                            sendLiveEventData(REMOVE_FAVORITE_APPS,appInfo)
                        }
                    }
                }
                true
            }
        }
    }

    var isMoveLocalAppStatus = false
    fun BindAdapter.swapItems(fromPosition: Int, toPosition: Int) {
        Collections.swap(this.models, fromPosition, toPosition)
        this.dslAdapter.notifyItemMoved(fromPosition, toPosition)
    }


}